package com.tcxhb.job.core.schedule.router;

import com.tcxhb.job.dao.dataobject.JobMachineDO;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/18
 */
@Component
public class RouterRandom extends BaseRouter {
    @Override
    public List<JobMachineDO> route(int num, List<JobMachineDO> list) {
        return random(num,list);
    }

    @Override
    public JobMachineDO route(List<JobMachineDO> list) {
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        Random rand = new Random();
        int idx = rand.nextInt(list.size());
        return list.get(idx);
    }

    /**
     * @param num
     * @param list
     * @return
     */
    public List<JobMachineDO> random(int num, List<JobMachineDO> list) {
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        Random rand = new Random();
        if (num >= list.size()) {
            return list;
        }
        //大概率是1走随机
        if (num == 1) {
            int idx = rand.nextInt(list.size());
            return Arrays.asList(list.get(idx));
        }
        //随机数
        List<JobMachineDO> result = new ArrayList<>();
        int len = list.size();
        for (int i = 0; i < num; i++) {
            int idx = rand.nextInt(len);
            result.add(list.get(idx));
            if (idx != len - 1) {
                //把后面的换到前面去
                list.set(idx, list.get(len - 1));
            }
            len = len - 1;
        }
        return result;
    }
}
